#include "Define.h"


void IFBIT(void)
{
	//bit and err manage
	if(g_CanMsg.ErrState.bit.MotorIOver == 0)
	{
		g_CanMsg.ErrState.bit.MotorIOver = MOT_MotorITest();
	}
	//if(g_CanMsg.ErrState.bit.MotorUUnder == 0)
	//{
	g_CanMsg.ErrState.bit.MotorUUnder = MOT_MotorUTest();
	//}
	if(g_CanMsg.ErrState.bit.SpeedOver == 0)
	{
		g_CanMsg.ErrState.bit.SpeedOver = MOT_SpeedTest();
	}
}

Uint16 MOT_MotorITest(void)
{
    Uint16 uiTestResult = 0;
	static Uint16 s_ErrCnt = 0U;

	if( g_SysData.AnalogData.Items.MOTOR_I <= VAL_MOTOR_I_LMT )
	{
		s_ErrCnt = 0u;
	}
	else
	{
		s_ErrCnt++;
	}

	if( s_ErrCnt < 100u )
	{
		uiTestResult = 0;
	}
	else
	{
		uiTestResult = 1;
		s_ErrCnt = 100u;
	}

    return uiTestResult;
}

Uint16 MOT_MotorUTest(void)
{
    Uint16 uiTestResult = 0;
	static Uint16 s_ErrCnt = 0U;

	if( g_CanMsg.MotorV >= VAL_MOTOR_U_LMT )
	{
		s_ErrCnt = 0u;
	}
	else
	{
		s_ErrCnt++;
	}

	if( s_ErrCnt < 100u )
	{
		uiTestResult = 0;
	}
	else
	{
		uiTestResult = 1;
		s_ErrCnt = 100u;
	}

    return uiTestResult;
}

static Uint16 timeCnt = 0U;
Uint16 MOT_SpeedTest(void)
{
	float32 err1 = fabs(dmc.fSpdRef - dmc.fSpdFb);
	float32 err2 = fabs(dmc.fSpdRef - dmc.fSpdRefRamp);
	Uint16 rst = 0U;

	if(dmc.uiEn == 1)
	{
	    timeCnt = ((err1 > 0.3f) && (err2 < 0.01f)) ? (timeCnt + 1) : 0;
	    if(timeCnt >= 100)
	    {
	        rst = 1U;
	        timeCnt = 100U;
	    }
	    else
	    {
	        rst = 0U;
	    }
	}
	else
	{
	    timeCnt = 0;
	}

	return rst;
}

/*---------------------------------------------------------------------------
 * End of file.
 *--------------------------------------------------------------------------*/
